package com.xiaodao.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * 关于buffer 的scattering 和 gathering
 * Created by xiaodao
 * date: 2019/12/7
 */
public class NioTest11 {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        socketChannel.bind(new InetSocketAddress(8899));
        int messageLength = 2+3+4;
        ByteBuffer[] byteBuffers =  new ByteBuffer[3];
        byteBuffers[0] = ByteBuffer.allocate(2);
        byteBuffers[1] = ByteBuffer.allocate(3);
        byteBuffers[2] = ByteBuffer.allocate(4);

        SocketChannel accept = socketChannel.accept();
        while (true){
            int bytesRead = 0;
            while (bytesRead < messageLength){
                long read = accept.read(byteBuffers);
                bytesRead += read;
                System.out.println("bytesRead: "+ bytesRead);
                Arrays.asList(byteBuffers).stream().map(byteBuffer -> "postion: "+ byteBuffer.position()+ " limit: "+ byteBuffer.limit())
                .forEach(System.out::println);
            }


            Arrays.asList(byteBuffers).forEach(it->it.flip());

            long writeLength = 0;

            while (writeLength < messageLength){
                long write = accept.write(byteBuffers);
                writeLength+= write;

            }
            Arrays.asList(byteBuffers).forEach(it->it.clear());
            System.out.println("bytesRead: "+ bytesRead+", writeLength "+ writeLength);
        }


    }
}
